#include "cf_www.h"
#include "cf_string.h"
#include "cf_common.h"
#include "cf_std.h"
int cf_cgi_parse_query(const char* query, const char* key, CFString* value)
{
	const char *_key, *value_start, *value_end;
	int key_len = strlen(key);
	int query_len = strlen(query);
	_key = strstr(query, key);
	if(_key && *(_key+key_len)=='=' && ((_key != query && *(_key-1) == '&')||(_key == query))){
		value_start = _key + key_len + 1;
		value_end = strchr(value_start, '&');
		if(value_end)
			value_end--;
		else
			value_end = query + query_len -1;
		cf_string_safe_cp_n(value, value_start, value_end - value_start + 1);
		return 0;
	}else{
		return -1;
	}
}

int cf_cgi_parse_query_int(const char* qCStr, const char* key, int* value)
{
    CFString* tmpStr = cf_string_new("");
    if(cf_cgi_parse_query(qCStr, key, tmpStr)){
        goto OUT_FREE_TMP_STR;
    }
    *value = atoi(cf_string_get_str(tmpStr));
    cf_string_free(tmpStr);
    return 0;
OUT_FREE_TMP_STR:
    cf_string_free(tmpStr);
    return -1;
}

int cf_cgi_parse_query_double(const char* qCStr, const char* key, double* value)
{
    CFString* tmpStr = cf_string_new("");
    const char* tmpCStr;
    if(cf_cgi_parse_query(qCStr, key, tmpStr)){
        goto OUT_FREE_TMP_STR;
    }
    tmpCStr = cf_string_get_str(tmpStr);
    if(sscanf(tmpCStr, "%lf", value) != 1){
        goto OUT_FREE_TMP_STR;
    }
    cf_string_free(tmpStr);
    return 0;
OUT_FREE_TMP_STR:
    cf_string_free(tmpStr);
    return -1;
}